import { onMounted, reactive } from 'vue'
import {
  findUserDatabasesReq,
  syncDbMetaReq
} from '@/service/modules/data-manage'
import { DatabaseInfo } from '@/service/modules/data-manage/types'
import { useRouter } from 'vue-router'

export function useTable() {
  const router = useRouter()
  const state = reactive({
    list: [] as Array<DatabaseInfo>,
    loading: false,
    currentRecord: {} as DatabaseInfo
  })

  const getList = async () => {
    if (state.loading) return
    state.loading = true

    const { data } = await findUserDatabasesReq()
    state.loading = false
    if (!data) throw Error()
    state.list = [data]
  }

  const openTableListTab = (
    dsType: string,
    datasourceId: number,
    dsName: string,
    databaseId: number,
    dbName: string
  ) => {
    router.push({
      path: '/dataManage/dataCatalog/tableList',
      query: {
        tab:
          window.$t('dataManage.dbName') +
          `:${dbName} ` +
          window.$t('dataManage.tableList'),
        tabName: 'TableListTab',
        dsType: dsType,
        datasourceId: datasourceId,
        dsName: dsName,
        dbName: dbName,
        databaseId: databaseId
      }
    })
  }

  const syncDbMeta = async (databaseId: number) => {
    if (state.loading) return
    await syncDbMetaReq({ databaseId: databaseId })
    state.loading = false
  }

  const onOperationClick = (
    data: { rowData: DatabaseInfo },
    type: 'openTableListTab' | 'syncDbMeta'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'openTableListTab':
        openTableListTab(
          data.rowData.datasourceType,
          data.rowData.datasourceId,
          data.rowData.datasourceName,
          data.rowData.id,
          data.rowData.dbName
        )
        break
      case 'syncDbMeta':
        syncDbMeta(data.rowData.id)
        break
    }
  }

  onMounted(() => {
    getList()
  })

  return {
    state,
    onOperationClick
  }
}
